package com.asman.vr.network

import com.asman.vr.constant.UrlConst
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import log
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object ApiService {

    // todo BuildConfig 没有，这里先写死 BuildConfig.OPEN_LOG = true

    var BASE_URL = UrlConst.SplashBaseUrl
        // if (BuildConfig.OPEN_LOG) UrlConst.SplashBaseUrl else BuildConfig.BASE_URL

    private fun loggerInterceptor(): HttpLoggingInterceptor {
        val logger = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger {
            log("APII：$it")
        })
        logger.level = HttpLoggingInterceptor.Level.BODY
        return logger
    }

     fun httpClient(): OkHttpClient.Builder {
         val builder = OkHttpClient.Builder()

         // todo BuildConfig 没有，这里先写死 BuildConfig.OPEN_LOG = true
         builder.addInterceptor(loggerInterceptor())
         /*if (BuildConfig.OPEN_LOG) {
             builder.addInterceptor(loggerInterceptor())
         }*/

         return builder.addInterceptor(RequestHeaderInterceptor())
             .connectTimeout(30, TimeUnit.SECONDS) //设置请求超时时间
             .readTimeout(30, TimeUnit.SECONDS)
             .writeTimeout(30, TimeUnit.SECONDS)
     }

    private val builder =
        Retrofit.Builder().baseUrl(BASE_URL).client(httpClient().build())
            .addCallAdapterFactory(CoroutineCallAdapterFactory())
            .addConverterFactory(GsonConverterFactory.create())

    private val retrofit = builder.build()

    fun <API> create(serviceClass: Class<API>): API = retrofit.create(serviceClass)

}